package com.pur.zsms.supplier.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.DayWeekUtil;
import com.pur.zsms.ordercustommanage.po.OrderSupplierPo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierVo;
import com.pur.zsms.ordercustommanage.vo.OrderSupplierVoFooter;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.storemanage.service.IStoreService;
import com.pur.zsms.storemanage.vo.StoreInVo;
import com.pur.zsms.storemanage.vo.StoreMaterVo;
import com.pur.zsms.supplier.service.ISupplierOrderService;
import com.pur.zsms.supplier.service.ISupplierService;

@Controller
@RequestMapping(value = "/supporder")
public class SupplierOrderController {
	@Resource(name = "supplierOrderService")
	private ISupplierOrderService supplierOrderService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "storeService")
	private IStoreService storeService;

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(SupplierController.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/findSuppOrder.do")
	@ResponseBody
	public String findSuppOrder(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			OrderSupplierVo orderSupplierVo, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		log.info("----");
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		UserPo userInfo = (UserPo) session.getAttribute("user");
		// 根据用户id得出supid
		int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
		orderSupplierVo.setOrdSupId(supId);

		this.pageList = supplierOrderService.listSupplierOrder(pageController, orderSupplierVo);
		List<OrderSupplierVo> orderSupplierVoList = new ArrayList<OrderSupplierVo>();
		List<OrderSupplierVoFooter> orderSupplierVoListFooter = new ArrayList<OrderSupplierVoFooter>();
		BigDecimal ordValueReal = new BigDecimal(0);
		BigDecimal ordValueRealCost = new BigDecimal(0);
		BigDecimal turnover = new BigDecimal(0);
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				OrderSupplierVo f = new OrderSupplierVo();

				f.setOid((Integer) item[0]);
				f.setOrdId((Integer) item[1]);
				f.setOrdCustId((Integer) item[2]);
				f.setOrdSupId((Integer) item[3]);
				f.setOrdState((Integer) item[4]);
				f.setOrdDate((String) item[5]);
				f.setOrdDay((String) item[6]);
				f.setOrdValue((BigDecimal) item[9]);
				f.setOrdCustName((String) item[10]);
				f.setOrdSupName((String) item[11]);
				f.setOrdPaymentState((Integer) item[12]);
				if (item[13] != null) {
					f.setOrdValueReal((BigDecimal) item[13]);
					ordValueReal = ordValueReal.add(new BigDecimal(item[13].toString()));
				} else {
					f.setOrdValueReal(null);
				}

				f.setCommitDeliverState((Integer) item[14]);
				if (item[15] != null) {
					f.setOrdValueRealCost(new BigDecimal((String) item[15]));
					ordValueRealCost = ordValueRealCost.add(new BigDecimal(item[15].toString()));
				} else {
					f.setOrdValueRealCost(null);
				}
				if (item[16] != null) {
					f.setGrossMargin(item[16].toString() + "%");
				} else {
					f.setGrossMargin("无");
				}
				if (item[17] != null) {
					f.setTurnover(new BigDecimal(item[17].toString()));
					turnover = turnover.add(new BigDecimal(item[17].toString()));
				} else {
					f.setTurnover(new BigDecimal(0));
				}
				if (item[18] != null) {
					f.setCode(item[18].toString());
				}
				f.setOrdStateSup((Integer) item[19]);
				f.setContent("查看详细清单");
				orderSupplierVoList.add(f);
			}
		}

		OrderSupplierVoFooter footer = new OrderSupplierVoFooter();
		footer.setOrdCustName("合计");
		footer.setOrdValueRealCost(ordValueRealCost);
		footer.setOrdValueReal(ordValueReal);
		footer.setTurnover(turnover);
		String grossMargin = "无";
		if (ordValueReal.compareTo(new BigDecimal(0)) != 0) {
			grossMargin = (ordValueReal.subtract(ordValueRealCost)).multiply(new BigDecimal(100)).divide(ordValueReal, 2, BigDecimal.ROUND_HALF_UP)
					.toString()
					+ "%";
		}

		footer.setGrossMargin(grossMargin);
		orderSupplierVoListFooter.add(footer);
		json.put("footer", orderSupplierVoListFooter);

		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", orderSupplierVoList);
		log.info("----" + json.toString());
		return json.toString();
	}

	@RequestMapping(value = "/sendOrderSupplier.do", method = { RequestMethod.POST })
	@ResponseBody
	public String sendOrderSupplier(String ordId, String ordCustId, String ordSupId, String ordDate, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			orderSupplierPo = supplierOrderService.getOrderSup(ordId, ordCustId, ordSupId);
			supplierOrderService.sendmater(orderSupplierPo);

			List<StoreMaterVo> storeMaterVoList = new ArrayList<StoreMaterVo>();

			List list = supplierOrderService.getOrderSupMaterReal(ordId, ordCustId, ordSupId);

			for (int i = 0; i < list.size(); i++) {
				Object[] item = (Object[]) list.get(i);
				StoreMaterVo tStoreMaterVo = new StoreMaterVo();
				tStoreMaterVo.setMaterId((Integer) item[0]);
				tStoreMaterVo.setMaterNum(new BigDecimal(item[1].toString()));
				tStoreMaterVo.setMaterLevel((Integer) item[2]);
				storeMaterVoList.add(tStoreMaterVo);
			}

			int storeHouseId = storeService.getStoreHouseIdByCustId(ordCustId);

			UserPo userInfo = (UserPo) session.getAttribute("user");
			StoreInVo storeInVo = new StoreInVo();
			storeInVo.setCreatDate(ordDate);
			storeInVo.setStoreHouseId(storeHouseId);
			storeInVo.setStoreInState(1);// 状态未确认
			storeInVo.setStoreInWay(2);// 自动入库
			storeInVo.setOrdId(Integer.valueOf(ordId));
			storeInVo.setSupId(Integer.valueOf(ordSupId));// 供货商
			storeInVo.setSupSupId(0);

			int custId = Integer.valueOf(ordCustId);
			int storeInId = storeService.addStoreIn(storeInVo, custId);
			storeService.addStoreInDetailed(storeMaterVoList, storeInId);
			// 生成入库订单
			// OrderSupplierMaterPo tOrderSupplierMaterPo = new
			// OrderSupplierMaterPo();

			// tOrderSupplierMaterPo=supplierOrderService.getOrderSup(ordId,
			// ordCustId, ordSupId);

			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	@RequestMapping(value = "/renturnSendmater.do", method = { RequestMethod.POST })
	@ResponseBody
	public String renturnSendmater(String ordId, String ordCustId, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			// 根据用户id得出supid
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			orderSupplierPo = supplierOrderService.getOrderSup(ordId, ordCustId, String.valueOf(supId));
			boolean flag = supplierOrderService.renturnSendmater(orderSupplierPo);
			if (!flag) {
				json.put("success", false);
				json.put("msg", supplierOrderService.getMsg());
			} else {
				json.put("success", true);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}
	/**
	 * 修改订单时间*/
	@RequestMapping(value = "/updateOrderDate.do", method = { RequestMethod.POST })
	@ResponseBody
	public String updateOrderDate(String ordId, String ordCustId,String orderDate, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			// 根据用户id得出supid
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			orderSupplierPo = supplierOrderService.getOrderSup(ordId, ordCustId, String.valueOf(supId));
			
			orderSupplierPo.setOrdDate(orderDate);
			orderSupplierPo.setOrdDay(DayWeekUtil.getDay(orderDate));
			boolean flag = supplierOrderService.updateOrderDate(orderSupplierPo);

			if (!flag) {
				json.put("success", false);
				json.put("msg", supplierOrderService.getMsg());
			} else {
				json.put("success", true);
			}
			
			
			
			//new update
			

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	// 订单审核
	@RequestMapping(value = "/reviewOrderSup.do", method = { RequestMethod.POST })
	@ResponseBody
	public String reviewOrderSup(String ordId, String ordCustId, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			// 根据用户id得出supid
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			orderSupplierPo = supplierOrderService.getOrderSup(ordId, ordCustId, String.valueOf(supId));
			boolean flag = supplierOrderService.reviewOrderSup(orderSupplierPo);
			if (!flag) {
				json.put("success", false);
				json.put("msg", supplierOrderService.getMsg());
			} else {
				json.put("success", true);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	@RequestMapping(value = "/reconciliationForSup.do", method = { RequestMethod.POST })
	@ResponseBody
	public String reconciliationForSup(String ordId, String ordCustId, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			// 根据用户id得出supid
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			orderSupplierPo = supplierOrderService.getOrderSup(ordId, ordCustId, String.valueOf(supId));
			boolean flag = supplierOrderService.reconciliationForSup(orderSupplierPo);
			if (!flag) {
				json.put("success", false);
				json.put("msg", supplierOrderService.getMsg());
			} else {
				json.put("success", true);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	@RequestMapping(value = "/clearingForSup.do", method = { RequestMethod.POST })
	@ResponseBody
	public String clearingForSup(String ordId, String ordCustId, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			// 根据用户id得出supid
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			orderSupplierPo = supplierOrderService.getOrderSup(ordId, ordCustId, String.valueOf(supId));
			boolean flag = supplierOrderService.clearingForSup(orderSupplierPo);
			if (!flag) {
				json.put("success", false);
				json.put("msg", supplierOrderService.getMsg());
			} else {
				json.put("success", true);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	@RequestMapping(value = "/updateStateByLevel.do", method = { RequestMethod.POST })
	@ResponseBody
	public String updateStateByLevel(String ordId, String ordSupId) {
		JSONObject json = new JSONObject();
		try {
			OrderSupplierPo orderSupplierPo = new OrderSupplierPo();
			System.out.println("--------" + ordId);
			orderSupplierPo = supplierOrderService.getOrderSupByOrdIdSupId(ordId, ordSupId);
			supplierOrderService.updateOrderSupPoState(orderSupplierPo, 2);

			// 生成供应商订单
			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}
}
